package com.dr.service.impl;

import com.dr.Enum.ExcepEnum;
import com.dr.common.ution.DateUtil;
import com.dr.common.ution.VerifyCodeUtils;
import com.dr.db.WeChatLoginMapper;
import com.dr.exception.ServiceExcep;
import com.dr.pojo.WeChatLogin;
import com.dr.service.WeChatLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by tugou on 2017/5/23.
 */
@Service
public class WeChatLoginServiceImpl implements WeChatLoginService{

    @Autowired
    WeChatLoginMapper weChatLoginMapper;


    @Override
    public WeChatLogin createWeChatLoginInfo() throws ServiceExcep{
        WeChatLogin info = new WeChatLogin();
        info.setState(0);
        info.setQrcode(DateUtil.now()+ VerifyCodeUtils.generateVerifyCode(5));
        info.setCreateDate(DateUtil.now());
        int result = weChatLoginMapper.insertWeChatLogin(info);
        if(result != 0){
            return info;
        }
        else{
            throw new ServiceExcep(ExcepEnum.INSERTDATAEMPTY.getName(),ExcepEnum.INSERTDATAEMPTY.getIndex());
        }
    }

    @Override
    public void updateWeChatLogin(String code) throws ServiceExcep {
        WeChatLogin par = new WeChatLogin();
        par.setQrcode(code);
        WeChatLogin weChatLogin = weChatLoginMapper.getWeChatLoginByCode(par);
        if (weChatLogin != null && weChatLogin.getState() != null){
            if(weChatLogin.getState() == 0){
                weChatLogin.setState(1);
                weChatLoginMapper.updateWeChatLogin(weChatLogin);
            }
        }
        else{
            throw new ServiceExcep(ExcepEnum.QUERYRESULTISEMPTY.getName(),ExcepEnum.QUERYRESULTISEMPTY.getIndex());
        }
    }

    @Override
    public WeChatLogin getWeChatLoginByCode(String code) throws ServiceExcep {
        WeChatLogin par = new WeChatLogin();
        par.setQrcode(code);
        WeChatLogin weChatLogin = weChatLoginMapper.getWeChatLoginByCode(par);
        if (weChatLogin != null && weChatLogin.getState() != null){
            return weChatLogin;
        }
        else
            throw new ServiceExcep(ExcepEnum.QUERYRESULTISEMPTY.getName(),ExcepEnum.QUERYRESULTISEMPTY.getIndex());

    }
}
